/*
 * Copyright 2011-2013 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

Components.utils.import("resource://oaa-accessibility-extension/cache-inspector-common.js");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");


/**
 * @file sidebar-rule-summary.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_AE_SIDEBAR.RuleCategoryView Object             */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_AE_SIDEBAR.RuleCategoryView === "undefined") {
  OAA_AE_SIDEBAR.RuleCategoryView = {};
}


/* ---------------------------------------------------------------- */
/*       Rule Category Cache Item Views and View Controllers        */ 
/* ---------------------------------------------------------------- */

/**
 * @file sidebar-rule-category-view.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

Components.utils.import("resource://oaa-accessibility-extension/cache-inspector-common.js");

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_AE_SIDEBAR.RuleResultsSummary Object                  */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_AE_SIDEBAR.RuleCategoryView === "undefined") {
  OAA_AE_SIDEBAR.RuleCategoryView = {};
}

/* ---------------------------------------------------------------- */
/*                  Rule Summary View Control Functions             */ 
/* ---------------------------------------------------------------- */


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.initStrings
 *
 * @desc Initializes message strings for view
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.initStrings = function () {

  if (typeof this.MSG_UPDATING !== 'string') {
  
    var nls_strings  = OAA_AE_SIDEBAR.nls_strings;

    if (!nls_strings) return;
  
    this.MSG_UPDATING                   = nls_strings.getString('updating');
    this.MSG_ELEMENTS                   = nls_strings.getString('elements');
    this.MSG_RESULTS_FOR                = nls_strings.getString('resultsFor');
    this.MSG_NO_RULES                   = nls_strings.getString('noRules');
    this.MSG_NO_RULES_GUIDELINE         = nls_strings.getString('noRulesGuideline');
    this.MSG_NO_RULES_PRINCIPLE         = nls_strings.getString('noRulesPrinciple');
    this.MSG_NO_RULES_SUCCESS_CRITERION = nls_strings.getString('noRulesSuccessCriterion');
    this.MSG_RULE                       = nls_strings.getString('rule');
    this.MSG_INFORMATION                = nls_strings.getString('information');
    this.MSG_NO_RULE_SELECTED           = nls_strings.getString('noRuleSelected');
    this.MSG_RESULT_MESSAGE             = nls_strings.getString('resultMessage');
    this.MSG_HIGHLIGHT_ELEMENTS         = nls_strings.getString('highlightElements');
    this.MSG_HIGHLIGHT_REMOVE           = nls_strings.getString('highlightRemove');
    this.MSG_ELEMENT_RESULTS_FOR_RULE   = nls_strings.getString('elementResultsForRule');
    
    this.MSG_MORE_INFORMATION_RULE = nls_strings.getString('moreInformationRule');
  }  

};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.hide
 *
 * @desc Hides the XUL elements of the rule results view
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.hide = function () {

  var vbox_rule_category   = window.document.getElementById('ID_VBOX_RULE_CATEGORY_VIEW');

  vbox_rule_category.hidden = true;
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.show
 *
 * @desc Shows the rule results summary view
 *
 * @param {Boolean}  tree  -  True if the list a tree
 *
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.show = function (tree) {

  var vbox_rule_category  = window.document.getElementById('ID_VBOX_RULE_CATEGORY_VIEW');
  var treecol_primary     = window.document.getElementById('ID_TREECOL_RULE_CATEGORY_DESCRIPTION');
  
  vbox_rule_category.hidden = false;
  
  if (typeof tree === 'boolean' && tree) treecol_primary.setAttribute('primary', 'true');
  else treecol_primary.setAttribute('primary', 'false');
  
//  var state = this.treecol_primary.getAttribute('primary')
  
//  OAA_AE_SIDEBAR.logger.debug("  PRIMARY: " + state);
  
};


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.clear
 *
 * @desc Clears the rule results summary view with a "updating" message
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.clear = function () {

  this.initStrings();

//  OAA_AE_SIDEBAR.logger.debug("  Rule Category Clear: Start ");
  
  this.visible_tree_items = [];          
  
  var str_message = OAA_AE_SIDEBAR.RuleCategoryView.MSG_UPDATING;
 
  var row = { level : 0,
              container : false,
              open : false,
            
              message : str_message,
              message_prop : 'message'
            };
  
  this.visible_tree_items.push(row);               

  this.ruleButtonMessageClear();

  OAA_AE_SIDEBAR.RuleResultView.clear();

  this.setView();

};


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.hideTreeControls
 *
 * @desc Shows the rule category sidebar and updates the contents
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.hideTreeControls = function () {

  var tree_controls = document.getElementById('ID_HBOX_RULE_CATEGORY_EXPAND');
  tree_controls.setAttribute('hidden', 'true');

  var primary_treecol = document.getElementById('ID_TREECOL_RULE_CATEGORY_DESCRIPTION');  
  primary_treecol.setAttribute('primary', 'false');
    
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.showTreeControls
 *
 * @desc Shows the rule category sidebar and updates the contents
 *
 * @param {Boolean}  flag  - Boolean indicating whether tree controls should be hidden
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.showTreeControls = function (flag) {

  if (typeof flag !== 'boolean') flag = true;

  var tree_controls = document.getElementById('ID_HBOX_RULE_CATEGORY_EXPAND');
  
  tree_controls.setAttribute('hidden', 'false');

  var primary_treecol = document.getElementById('ID_TREECOL_RULE_CATEGORY_DESCRIPTION');
  
  var expand_tree = document.getElementById('ID_BUTTON_RULE_CATEGORY_EXPAND_TREE');
  var collapse_tree = document.getElementById('ID_BUTTON_RULE_CATEGORY_COLLAPSE_TREE');
  
  if (flag) {
    primary_treecol.setAttribute('primary', 'true');
    
    expand_tree.setAttribute('disabled', 'false');
    collapse_tree.setAttribute('disabled', 'false');    
  } 
  else {
    primary_treecol.setAttribute('primary', 'false');
    
    expand_tree.setAttribute('disabled', 'true');
    collapse_tree.setAttribute('disabled', 'true');
  } 
  
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.showTreeControls
 *
 * @desc Shows the rule category sidebar and updates the contents
 *
 * @param {Boolean}  flag - true if all expanded, otherwise false if all collapsed
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.showTree = function (flag) {

  var tree_view = OAA_AE_SIDEBAR.RuleCategoryView.tree_view;

//  OAA_AE_SIDEBAR.logger.debug("FRC: " + frc + "  IS TREE: " + (frc ? frc.is_tree : null));

  if (tree_view) {
  
    OAA_AE_SIDEBAR.RuleCategoryView.showTreeControls(true);

//    OAA_AE_SIDEBAR.logger.debug("IS Open: " + flag);

    tree_view.setOpenState(flag);
   
    // Update the columns displayed
    
    OAA_AE_SIDEBAR.RuleCategoryView.visible_tree_items = tree_view.getOpenRuleResults();

    OAA_AE_SIDEBAR.RuleCategoryView.setView();    
    
  }
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.updateViewNameAndSummary
 *
 * @desc Initializes and shows the rule category and summary views
 */
  
OAA_AE_SIDEBAR.RuleCategoryView.updateViewNameAndSummary = function () {

  if (this.summary_data) OAA_AE_SIDEBAR.setSummaryValues(this.summary_data);
  else OAA_AE_SIDEBAR.setSummaryValues();

  var view_name    = window.document.getElementById('ID_VIEW_NAME');

  if (!view_name) return;

  view_name.setAttribute('value', OAA_AE_SIDEBAR.view.nls_title);
  view_name.setAttribute('control', 'ID_TREE_RULE_CATEGORY_VIEW');

};


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.update
 *
 * @desc Initializes and shows the rule category and summary views
 */
  
OAA_AE_SIDEBAR.RuleCategoryView.update = function () {

  var tree         = window.document.getElementById('ID_TREE_RULE_CATEGORY_VIEW');

  this.initStrings();

  if (!tree) return;
    
  this.rule_result_items = [];
  this.rule_result_item  = null;
  
  var prefs = OAA_WEB_ACCESSIBILITY_PREF.util.getPreferences();
    
  var sidebar_option = OAA_AE_SIDEBAR.view.option;
  var sidebar_type   = OAA_AE_SIDEBAR.view.type;

  var frc           = null;
  var frc_tree_view = null;

  switch (sidebar_type) {
  
    case 'category':
      frc = OAA_AE_SIDEBAR.evaluation_result.getFilteredRuleResultsByRuleCategory(sidebar_option, prefs.show_results_filter_value);
      break;
      
    case 'guideline':
      frc = OAA_AE_SIDEBAR.evaluation_result.getFilteredRuleResultsByGuideline(sidebar_option, prefs.show_results_filter_value);
      break;
      
    case 'principle':
      frc = OAA_AE_SIDEBAR.evaluation_result.getFilteredRuleResultsByPrinciple(sidebar_option, prefs.show_results_filter_value);
      break;
      
    case 'success_criteria':
      frc = OAA_AE_SIDEBAR.evaluation_result.getFilteredRuleResultsBySuccessCriterion(sidebar_option, prefs.show_results_filter_value);
      break;
      
    default:
      break;
  }    

  
  if (frc) {
  
    OAA_AE_SIDEBAR.RuleCategoryView.filtered_rule_category = frc;
    OAA_AE_SIDEBAR.RuleCategoryView.tree_view = null;
  
    OAA_AE_SIDEBAR.RuleCategoryView.highlightNodeResults(false);
    
//    OAA_AE_SIDEBAR.logger.debug("  Number of Rules: " + frc.getNumberOfRules() + " has rules: " + frc.hasRules() + " has results: " + frc.hasResults());

    if (frc.hasRules()) {
    
      frc_tree_view = new OpenAjax.a11y.formatters.TreeViewOfFilteredRuleResultsGroup(frc);

//      OAA_AE_SIDEBAR.logger.debug("  tree view: " + frc_tree_view + " " + (typeof frc_tree_view.sortListOfRuleResults));

      frc_tree_view.sortListOfRuleResults('wcag20_level', -1);  
    
      OAA_AE_SIDEBAR.RuleCategoryView.tree_view = frc_tree_view;
        
      this.hideTreeControls();

      this.summary_data = frc.getRuleResultsSummary();
      this.visible_tree_items = frc_tree_view.getOpenRuleResults();
    }
    else {

      this.visible_tree_items = [];          
      
      var str_message = this.MSG_NO_RULES;
      if (sidebar_type === 'guideline')         str_message = this.MSG_NO_RULES_GUIDELINE;
      if (sidebar_type === 'principle')         str_message = this.MSG_NO_RULES_PRINCIPLE;
      if (sidebar_type === 'success_criterion') str_message = this.MSG_NO_RULES_SUCCESS_CRITERION;

      var row = { level : 0,
                  container : false,
                  open : false,
            
                  message : str_message,
                  message_prop : 'message'
                };
  
      this.visible_tree_items.push(row);               

      this.summary_data = new OpenAjax.a11y.RuleResultsSummary();
    }
    
  }
  else {
    frc = OAA_AE_SIDEBAR.evaluation_result.getFilteredRuleResultsByRuleSummary(sidebar_option, prefs.show_results_filter_value);
    OAA_AE_SIDEBAR.RuleCategoryView.filtered_rule_category = frc;

//    OAA_AE_SIDEBAR.logger.debug("Number of groups: " + frc.filtered_rule_results_groups.length);

    frc_tree_view = new OpenAjax.a11y.formatters.TreeViewOfFilteredRuleResultsGroups(frc);
    OAA_AE_SIDEBAR.RuleCategoryView.tree_view = frc_tree_view;

    // use default sorting
    frc_tree_view.sortListOfRuleResults(); 
    
    this.showTreeControls(true);

    this.summary_data = frc.getRuleResultsSummary();

    this.visible_tree_items = frc_tree_view.getOpenRuleResults();

//    if (frc_tree_view) OAA_AE_SIDEBAR.logger.debug("Created list of groups: " + frc_tree_view.rule_result_items.length);
//    else OAA_AE_SIDEBAR.logger.debug("Created list of groups: no groups");

  }

  OAA_AE_SIDEBAR.logger.debug("Rule Summary Information: " + frc.getRuleResultsSummary());

  OAA_AE_SIDEBAR.RuleCategoryView.updateViewNameAndSummary();

  OAA_AE_SIDEBAR.showRuleGroupInformation(frc, true);
  
  var IOM = OAA_AE_SIDEBAR.INFORMATION_OPTION;
  OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_VIEW);
  
  OAA_AE_SIDEBAR.RuleCategoryView.setView();
  
};  
  
/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.setView
 *
 * @desc Updates tree view
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.setView = function () {  

//  OAA_AE_SIDEBAR.logger.debug("Update View: " + this.rule_result_items.length);

  var tree         = window.document.getElementById('ID_TREE_RULE_CATEGORY_VIEW');

  var visible_tree_items = OAA_AE_SIDEBAR.RuleCategoryView.visible_tree_items;
  
  var treeView = {
    visibleData : visible_tree_items,
     
    selection   : null,
    treeBox     : null,
 
    isSeparator: function(row){ return false; },
    isSorted: function(){ return false; },
    getImageSrc: function(row,col){ return null; },        
    getRowProperties: function(row){ return ""; },
    getColumnProperties: function(colid,col){  return "";  },
    cycleHeader : function(col, elem) {},

    setTree     : function(treeBox) { 
      this.treeBox = treeBox; 
    },
        
    get rowCount() { 
      return this.visibleData.length;
    },
    
    getCellText : function(row,column) {
     
       var item      = this.visibleData[row];
       
//       OAA_AE_SIDEBAR.logger.debug("  Cell Text: " + row + " of " + rr_items_len + ": " + column.id);

       switch (column.id) {
       
       case "ID_TREECOL_RULE_CATEGORY_DESCRIPTION":
          if (item.summary) return item.summary;
          if (item.message) return item.message;
          break;
       
       case "ID_TREECOL_RULE_CATEGORY_REQUIRED": 
//           OAA_AE_SIDEBAR.logger.debug( row + " " + column.id + "  Item: " + item + " Required Label: " + item.required_label);
           if (item.required_label) return item.required_label;      
         
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_LEVEL":
         return item.wcag20_level_label;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_PERCENT_PASSED":
         return item.percent_passed_label;
         break;

       case "ID_TREECOL_RULE_CATEGORY_PASSED":
         return item.passed_label;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_WARNINGS":
         return item.warnings_label;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_VIOLATIONS":
         return item.violations_label;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_FAILURES":
         return item.failures_label;
         break;
         
       case "ID_TREECOL_RULE_CATEGORY_MANUAL_CHECKS":
         return item.manual_checks_label;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_HIDDEN":
         return item.hidden_label;
         break;
       
       default:
         break;
       }  

       return "";
     },
     isContainer: function(row) { 

       var item = this.visibleData[row];

//       OAA_AE_SIDEBAR.logger.debug("  CONTAINER: " + item.summary + " " + item.container);

       return item.container; 
       
     },
     isContainerEmpty: function(row) { 

       var item  = this.visibleData[row];

//       OAA_AE_SIDEBAR.logger.debug("  EMPTY: " + item.summary + " " + item.container);

       return (typeof item.children !== 'object') || (item.children.length == 0); 
       
     },
     getParentIndex: function(row) {
        
       if (!this.isContainer(row)) {
         for (var t = row - 1; t >= 0 ; t--) {
           if (this.isContainer(t)) return t;
         }
       }
           
       return -1;
     },
     hasNextSibling: function(row, afterIndex) {
       var thisLevel = this.getLevel(row);
       for (var t = afterIndex + 1; t < this.visibleData.length; t++) {
         var nextLevel = this.getLevel(t);
         if (nextLevel == thisLevel) return true;
         if (nextLevel < thisLevel) break;
       }
       return false;     
     },
     isContainerOpen: function(row) { 

       var item     = this.visibleData[row];

//       OAA_AE_SIDEBAR.logger.debug("  OPEN: " + item.summary + " " + item.open);

       return item.open; 
       
     },
     getLevel: function(row) { 

       var item     = this.visibleData[row];

//       OAA_AE_SIDEBAR.logger.debug("  LEVEL: " + item.summary + " " + item.level);
       
       return item.level; 
       
     },
     toggleOpenState: function(row){ 

       var item = this.visibleData[row];

       if (!item.container) return;

       if (item.open) {
         item.open = false;
 
         var thisLevel = this.getLevel(row);
         var deletecount = 0;
         for (var t = row + 1; t < this.visibleData.length; t++) {
           if (this.getLevel(t) > thisLevel) deletecount++;
           else break;
         }

         if (deletecount) {
           this.visibleData.splice(row + 1, deletecount);
           this.treeBox.rowCountChanged(row + 1, -deletecount);
         }
       }
       else {
         item.open = true;
      
         var children_len = item.children.length;

         for (var i = 0; i < children_len; i++) {
           this.visibleData.splice(row + i + 1, 0, item.children[i]);
         }
      
         this.treeBox.rowCountChanged(row + 1, children_len);
       }
         
      this.treeBox.invalidateRow(row);
  
    },
    getCellProperties: function(row,column){

       var item = this.visibleData[row];
       
       var property_value = "";

       switch (column.id) {
              
       case "ID_TREECOL_RULE_CATEGORY_DESCRIPTION":
         if (item.summary_prop) property_value = item.summary_prop;
         if (item.message_prop) property_value = item.message_prop;
          break;
       
       case "ID_TREECOL_RULE_CATEGORY_REQUIRED":       
         property_value = item.required_prop;
         break;

       case "ID_TREECOL_RULE_CATEGORY_LEVEL":       
         property_value = item.wcag20_level_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_PERCENT_PASSED":
         property_value = item.percent_passed_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_PASSED":
         property_value = item.passed_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_WARNINGS":
         property_value = item.warnings_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_VIOLATIONS":
         property_value = item.violations_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_FAILURES":
         property_value = item.failures_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_MANUAL_CHECKS":
         property_value =  item.manual_checks_prop;
         break;
       
       case "ID_TREECOL_RULE_CATEGORY_HIDDEN":
         property_value =  item.hidden_prop;
         break;
       
       default:
         break;
       }  

       return property_value;

     }
   };
   
  tree.view = treeView;
  
//  OAA_AE_SIDEBAR.logger.debug("Update View: TREE " + tree.id + " " + tree.view + " " + treeView);
 
  this.rule_result_item = null;    
  this.ruleButtonMessageClear();
  OAA_AE_SIDEBAR.RuleResultView.clear();
  
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.sortRuleList
 *
 * @desc Sorts the list of rules by a sort property
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.sortRuleList = function (column) {
  
  var tree = window.document.getElementById('ID_TREE_RULE_CATEGORY_VIEW');

  var column_name;
  var order = tree.getAttribute("sortDirection") == "ascending" ? 1 : -1;
  
  //if the column is passed and it's already sorted by that column, reverse sort
  if (column) {
    column_name = column.id;

    if (tree.getAttribute("sortResource") == column_name) {
      order *= -1;
    }
  } else {
    column_name = tree.getAttribute("sortResource");
  }

  //setting these will make the sort option persist
  tree.setAttribute("sortDirection", order == 1 ? "ascending" : "descending");
  tree.setAttribute("sortResource", column_name);
  
  //set the appropriate attributes to show to indicator
  var cols = tree.getElementsByTagName("treecol");

  for (var i = 0; i < cols.length; i++) {
    cols[i].removeAttribute("sortDirection");
  }

  document.getElementById(column_name).setAttribute("sortDirection", order == 1 ? "ascending" : "descending");

  var tree_view = OAA_AE_SIDEBAR.RuleCategoryView.tree_view;

  switch (column.id) {
       
  case "ID_TREECOL_RULE_CATEGORY_DESCRIPTION":
    tree_view.sortListOfRuleResults('summary', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_REQUIRED":       
    tree_view.sortListOfRuleResults('required', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_LEVEL":
    tree_view.sortListOfRuleResults('wcag20_level', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_PERCENT_PASSED":
    tree_view.sortListOfRuleResults('percent_passed', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_PASSED":
    tree_view.sortListOfRuleResults('passed_count', order);
    break;

  case "ID_TREECOL_RULE_CATEGORY_WARNINGS":
    tree_view.sortListOfRuleResults('warnings_count', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_VIOLATIONS":
    tree_view.sortListOfRuleResults('violations_count', order);
    break;

  case "ID_TREECOL_RULE_CATEGORY_FAILURES":
    tree_view.sortListOfRuleResults('failures_count', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_MANUAL_CHECKS":
    tree_view.sortListOfRuleResults('manual_checks_count', order);
    break;
       
  case "ID_TREECOL_RULE_CATEGORY_HIDDEN":
    tree_view.sortListOfRuleResults('hidden_count', order);
    break;
       
  default:
    break;
  }  
  
  this.visible_tree_items = tree_view.getOpenRuleResults();

  OAA_AE_SIDEBAR.RuleCategoryView.setView();

};


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.onSelect
 *
 * @desc Updates node results when a cache item is selected
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.onSelect = function () {

  var IOM = OAA_AE_SIDEBAR.INFORMATION_OPTION;

  var tree      = window.document.getElementById('ID_TREE_RULE_CATEGORY_VIEW');
  var tree_view = OAA_AE_SIDEBAR.RuleCategoryView.tree_view;
  
  OAA_AE_SIDEBAR.RuleCategoryView.visible_rule_item       = null;
  OAA_AE_SIDEBAR.RuleCategoryView.rule_result_item        = null;
  OAA_AE_SIDEBAR.RuleCategoryView.rule_results_group_item = null;
  OAA_AE_SIDEBAR.RuleCategoryView.is_a_rule               = false;

  if (tree) {

    var index = tree.currentIndex;

    var visible_tree_items = OAA_AE_SIDEBAR.RuleCategoryView.visible_tree_items;
    
    if (visible_tree_items && (index >= 0)) {

      var visible_rule_item = visible_tree_items[index];
      
      OAA_AE_SIDEBAR.RuleCategoryView.visible_rule_item = visible_rule_item;
      
      var rule_result_item        = visible_rule_item.filtered_rule_result;
      var rule_results_group_item = visible_rule_item.filtered_rule_results_group;

//      OAA_AE_SIDEBAR.logger.debug("OnSelect: " + "Rule Item: " + rule_result_item + " Group Item: " + rule_results_group_item);

      OAA_AE_SIDEBAR.RuleCategoryView.highlightNodeResults(false);
    
      if (rule_result_item) {
      
        OAA_AE_SIDEBAR.RuleCategoryView.rule_result_item = rule_result_item;
        OAA_AE_SIDEBAR.RuleCategoryView.is_a_rule = true;
        
        OAA_AE_SIDEBAR.showRuleResultInformation(rule_result_item, false);
        OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_SELECTION);
     
        OAA_AE_SIDEBAR.RuleResultView.update(rule_result_item);  

      }  
      else {

        OAA_AE_SIDEBAR.RuleResultView.clear();
        OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonMessageClear();

        if (rule_results_group_item) {
          OAA_AE_SIDEBAR.RuleCategoryView.rule_results_group_item = rule_results_group_item;
          OAA_AE_SIDEBAR.showRuleGroupInformation(rule_results_group_item);
          OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_SELECTION);
        }
        else {
          OAA_AE_SIDEBAR.showRuleGroupInformation(OAA_AE_SIDEBAR.RuleCategoryView.filtered_rule_category);
          OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_VIEW);
        }        
      }

      OAA_AE_SIDEBAR.RuleCategoryView.setElementButtons();

    }  
    else {
      OAA_AE_SIDEBAR.RuleResultView.clear();
      OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonMessageClear();
    }  
  } 
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.setHighlightButton
 *
 * @desc Highlight elements associated with a rule result object 
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.setHighlightButton = function(flag) {

  var node = window.document.getElementById('ID_BUTTON_RULE_CATEGORY_HIGHLIGHT');
  
  OAA_AE_SIDEBAR.RuleCategoryView.highlight = flag;
  
//  OAA_AE_SIDEBAR.logger.debug("  SET HIGHLIGHT: " + flag + " " + node);

  if (node) {
    if (flag) node.setAttribute('label', OAA_AE_SIDEBAR.RuleCategoryView.MSG_HIGHLIGHT_REMOVE);
    else node.setAttribute('label', OAA_AE_SIDEBAR.RuleCategoryView.MSG_HIGHLIGHT_ELEMENTS);
  }
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.highlightNodeResults
 *
 * @desc Highlight elements associated with a rule result object 
 */ 
 
OAA_AE_SIDEBAR.RuleCategoryView.highlightNodeResults = function(flag) {
  
  var rri = OAA_AE_SIDEBAR.RuleCategoryView.rule_result_item;
  
  if (typeof flag === 'boolean') OAA_AE_SIDEBAR.RuleCategoryView.setHighlightButton(flag);
  else OAA_AE_SIDEBAR.RuleCategoryView.setHighlightButton(!OAA_AE_SIDEBAR.RuleCategoryView.highlight);
  
//  OAA_AE_SIDEBAR.logger.debug("  RRI: " + rri);

  if (rri) {

    var nr  = rri.getNodeResults();
    if (nr && OAA_AE_SIDEBAR.RuleCategoryView.highlight) OAA_AE_SIDEBAR.highlightNodeResults(nr);
    else OAA_AE_SIDEBAR.highlightRemove();
    
  }
  else {
    OAA_AE_SIDEBAR.highlightRemove();
  }
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.setElementButtons
 *
 * @desc Enable or disable the show and highlight element buttons 
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.setElementButtons = function() {

  var tree = window.document.getElementById('ID_TREE_RULE_CATEGORY_VIEW');

  var flag = true;
  if (tree.currentIndex >= 0 && 
      OAA_AE_SIDEBAR.RuleCategoryView.is_a_rule &&
      OAA_AE_SIDEBAR.RuleCategoryView.rule_result_item &&
      OAA_AE_SIDEBAR.RuleCategoryView.rule_result_item.hasResults()) flag = false;
  
  var button_highlight = window.document.getElementById('ID_BUTTON_RULE_CATEGORY_HIGHLIGHT');
  var button_elements  = window.document.getElementById('ID_BUTTON_SHOW_ELEMENT_RESULTS');


  if (button_highlight &&  button_elements) {  
    button_highlight.disabled = flag;
    button_elements.disabled  = flag;
  }
};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.showElementResults
 *
 * @desc Show elements associated with a rule result object 
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.showElementResults = function() {

  if (OAA_AE_SIDEBAR.RuleCategoryView.is_a_rule) {

    OAA_AE_SIDEBAR.RuleResultView.updateViewNameAndSummary();
   
  };  
  
};


/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.showRuleInformation
 *
 * @desc Show information about the currently selected rule 
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.showRuleInformation = function () {

  if (this.rule_result_item && this.rule_result_item.rule_result) { 
    var rule_result = this.rule_result_item.rule_result;
    OAA_AE_SIDEBAR.showRulePropertiesDialog(rule_result);
    
  }
};

/* ---------------------------------------------------------------- */
/*        Rule Result Information Button and Message                */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonMessageClear
 *
 * @desc Clears the rules in the rules tabs
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonMessageClear = function () {

  var label_message             = window.document.getElementById('ID_LABEL_RULE_CATEGORY_MESSAGE'); 
  var textbox_message           = window.document.getElementById('ID_TEXTBOX_RULE_CATEGORY_MESSAGE');
 
  if (OAA_AE_SIDEBAR.rule_properties_dialog && 
      OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties) {
    OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties.clear();
  }

  if (textbox_message && label_message) {
    label_message.setAttribute('value', OAA_AE_SIDEBAR.RuleCategoryView.MSG_RULE + " " + OAA_AE_SIDEBAR.RuleCategoryView.MSG_RESULT_MESSAGE);
    textbox_message.setAttribute('value', OAA_AE_SIDEBAR.RuleCategoryView.MSG_NO_RULE_SELECTED);
  }

  this.rule_result_item = null;

};

/**
 * @function OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonUpdate
 *
 * @desc Updates the label of the show rule information button
 *
 * @param {FilteredRuleResult}  rule_result_item  - filtered rule result object   
 */
 
OAA_AE_SIDEBAR.RuleCategoryView.ruleButtonUpdate = function (rule_result_item) {

//  OAA_AE_SIDEBAR.logger.debug("Update button: " + rule_result_item.rule_result.getRule() + " (" + position + ")" );

  var tooltiptext;

  var button_rule_info  = window.document.getElementById('ID_BUTTON_SHOW_RULE_INFORMATION');
  var label_message     = window.document.getElementById('ID_LABEL_RULE_CATEGORY_MESSAGE');
  var textbox_message   = window.document.getElementById('ID_TEXTBOX_RULE_CATEGORY_MESSAGE');

  if (button_rule_info) {
  
    var rule_result = rule_result_item.rule_result;

    OAA_AE_SIDEBAR.showRuleResultInformation(rule_result_item, false);

//    OAA_AE_SIDEBAR.logger.debug("   Rule Result: " + rule_result.getRuleSummary());

    if (rule_result.getRuleSummary) {
    
      tooltiptext = OAA_AE_SIDEBAR.RuleCategoryView.MSG_MORE_INFORMATION_RULE + ": " + rule_result.getRuleSummary();

      button_rule_info.setAttribute("label", OAA_AE_SIDEBAR.RuleCategoryView.MSG_RULE + ' ' + OAA_AE_SIDEBAR.RuleCategoryView.MSG_INFORMATION);
      button_rule_info.setAttribute("tooltiptext",  tooltiptext);

      if (textbox_message && label_message) {
        label_message.setAttribute('value', OAA_AE_SIDEBAR.RuleCategoryView.MSG_RULE + " " + OAA_AE_SIDEBAR.RuleCategoryView.MSG_RESULT_MESSAGE);
        textbox_message.setAttribute('value', rule_result_item.rule_result.getMessage());
      }  

      if (OAA_AE_SIDEBAR.rule_properties_dialog && 
          OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties) {
        OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties.update(rule_result);
      }

    }
    else {

      OAA_AE_SIDEBAR.showRuleGroupInformation(rule_result);

      tooltiptext = OAA_AE_SIDEBAR.RuleCategoryView.MSG_NO_RULE_SELECTED;

      button_rule_info.setAttribute("label", OAA_AE_SIDEBAR.RuleCategoryView.MSG_RULE + ' ' + OAA_AE_SIDEBAR.RuleCategoryView.MSG_INFORMATION);
      button_rule_info.setAttribute("tooltiptext",  tooltiptext);
      button_rule_info.setAttribute("disabled", "true");
      
      if (OAA_AE_SIDEBAR.rule_properties_dialog && 
          OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties) {
        OAA_AE_SIDEBAR.rule_properties_dialog.rule_properties.clear();
      }
    }
  }
};
